<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stream Data Client</title>
</head>

<body>
    <div id="output"></div>
    <script>
        async function fetchStreamData() {
            try {
                // 发起请求
                const response = await fetch('http://localhost:3000/stream');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                // 获取响应的可读流
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                const outputDiv = document.getElementById('output');

                while (true) {
                    // 读取流中的数据
                    const { done, value } = await reader.read();
                    if (done) {
                        // 流读取完毕
                        console.log('Stream finished.');
                        break;
                    }

                    // 将 Uint8Array 转换为字符串
                    const chunk = decoder.decode(value);
                    // 将数据追加到页面上
                    outputDiv.textContent += chunk;
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }

        // 调用函数获取流式数据
        fetchStreamData();
    </script>
</body>

</html>